#include "MeshRenderer.h"


#include "../../Models/GameObject.h"
//#include "MeshFilter.h"
//class MeshFilter;

//////////////////////////////////////////////////////
//Constructor & Destructor
//////////////////////////////////////////////////////

MeshRenderer::MeshRenderer()
{
	_shader = ShaderManager::Instance()->GetShader("basic");
}

MeshRenderer::~MeshRenderer()
{
	_shader = NULL;
}


//////////////////////////////////////////////////////
//Runtime
//////////////////////////////////////////////////////

void MeshRenderer::Render(Matrix4 view, Matrix4 proj)
{
	MeshFilter* mesh = _gameObject->GetComponent<MeshFilter>();

	if(mesh == NULL)
		return;

	GLuint programObject = _shader->GetProgram();
	_shader->Bind();

	GLint modelviewUniform = glGetUniformLocation(programObject, "ModelViewMatrix");
	GLint projectionUniform = glGetUniformLocation(programObject, "ProjectionMatrix");
	glUniformMatrix4fv(projectionUniform, 1, 0, &proj.X.x);

	glUniformMatrix4fv(modelviewUniform, 1, 0, &view.X.x);


	GLint position_attribute = glGetAttribLocation(programObject, "Position");

	unsigned int vertexVBO = mesh->GetVertexVBO();
	unsigned int normalsVBO = mesh->GetNormalsVBO();
	unsigned int indexVBO = mesh->GetIndexVBO();
	unsigned int indexCount = mesh->GetIndexCount();


	glBindBuffer(GL_ARRAY_BUFFER, vertexVBO);
	glEnableVertexAttribArray(position_attribute);
	glVertexAttribPointer(position_attribute, 3, GL_FLOAT, GL_FALSE, 0, 0);
	GLint normal_attribute = glGetAttribLocation(programObject, "Normal");
	if (normal_attribute != -1)
	{
		glBindBuffer(GL_ARRAY_BUFFER, normalsVBO);
		glEnableVertexAttribArray(normal_attribute);
		glVertexAttribPointer(normal_attribute, 3, GL_FLOAT, GL_FALSE, 0, 0);
	}
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVBO);	
	//glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &numIndices);
	glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, 0);

	if (normal_attribute != -1)
		glDisableVertexAttribArray(normal_attribute);
	glDisableVertexAttribArray(position_attribute);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	
	_shader->Unbind();
}